package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ProcessInstanceStartPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.StringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ConstanceVariable;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowFormRepository;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.StartEvent;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Processor - 部署模型及节点关联的表单
 * <p>
 * copy一份表单的数据保存
 * </p>
 *
 * @author lilh
 * @date 2021/4/26 14:41
 */
@Slf4j
@Order(10)
@Component
public class DeployFormProcessor implements ProcessInstanceStartPostProcessor {

    @Autowired
    private FlowFormRepository flowFormRepository;

    @Override
    public void process(ExecutionEntity executionEntity) {
        BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(executionEntity.getProcessDefinitionId());
        formDeploy(executionEntity.getVariable(ConstanceVariable.PROCESS_INSTANCE_ID, String.class), bpmnModel);
    }

    private void formDeploy(String processInstanceId, BpmnModel bpmnModel) {
        // 关联相同的表单可以只部署一次
        Set<String> formKeys = new HashSet<>(16);
        Collection<FlowElement> flowElements = bpmnModel.getMainProcess().getFlowElements();
        for (FlowElement flowElement : flowElements) {
            if (flowElement instanceof StartEvent) {
                String formKey = ((StartEvent) flowElement).getFormKey();
                if (StringUtils.isNotEmpty(formKey)) {
                    formKeys.add(formKey);
                }
                continue;
            }

            if (flowElement instanceof UserTask) {
                String formKey = ((UserTask) flowElement).getFormKey();
                if (StringUtils.isNotEmpty(formKey)) {
                    formKeys.add(formKey);
                }
            }/**/
        }
        log.info("流程发起后，需要部署的表单key为：{}", formKeys);
        if (!formKeys.isEmpty()) {
            //部署表单
            formKeys.forEach(formKey -> flowFormRepository.deploy(formKey, processInstanceId));
        }
    }
}
